/********************************************************************************
 * Copyright (c)2016-2020, ShenZhen WanJiaAn Technology CO.,LTD.
 * All Rights Reserved.
 *
 * File Name     : DevTemperature.c
 * Author        : joki.zhu
 * Date          : 2020-05-21
 *
 * Record        :
 * 1.Date        : 2020-05-21
 *   Author      : joki.zhu
 *   Modification: Created file
 ********************************************************************************/
#include "app_common.h"
#include "OsdDraw.h"
 
static pthread_t g_tempProcPid;

void *tskTempProc(void *args)
{
    SET_THREAD_NAME("tskTempProc");
    pthread_detach(pthread_self());

    int ret = 0;
    int i = 0;
    float maxTempValue = 0;
    float minTempValue = 0;
    float totalTempValue = 0;
    float avgTempValue = 0;
    float arryTempValue[5] = {0.0};
    int arrySize = sizeof(arryTempValue)/sizeof(float);

    while (1)
    {
        i = 0;
        maxTempValue = 0;
        minTempValue = 0;
        totalTempValue = 0;
        avgTempValue = 0;
        memset(&arryTempValue, 0, sizeof(arryTempValue));
        
        for (i = 0; i < arrySize; i++)
        {
            ret = SocSubGetTemperature(&arryTempValue[i]);
            if (ret < 0) {
                goto err_continue;
            }

            if (i == 0) {
                maxTempValue = arryTempValue[i];
                minTempValue = arryTempValue[i];
            }
            
            maxTempValue = AV_MAX2(arryTempValue[i], maxTempValue);
            minTempValue = AV_MIN2(arryTempValue[i], minTempValue);
            totalTempValue += arryTempValue[i];
            
            if (i == (arrySize - 1)) {
                totalTempValue = totalTempValue - (maxTempValue + minTempValue);
                avgTempValue = totalTempValue / (arrySize -2);
            }
            usleep(200 * 1000);
        }

        OsdDrawSetTemperature(avgTempValue);
err_continue:
        sleep(1);
    }

    pthread_exit(0);
}

int TemperatureInit(void)
{
    int ret = 0;
    
    ret = pthread_create(&g_tempProcPid, NULL, (void *)tskTempProc, NULL);
    if (ret != 0) {
        LOGE("pthread_create tskTempProc failed\n");
        return -1;
    }

    return 0;
}


int TemperatureDeinit(void)
{
    pthread_cancel(g_tempProcPid);

    return 0;
}
